package cc.rengu.igas.momp.core.service.trans;

import cc.rengu.igas.momp.common.constant.CommonConstant;
import cc.rengu.igas.momp.common.dao.*;
import cc.rengu.igas.momp.common.dao.impl.*;
import cc.rengu.igas.momp.common.entity.*;
import cc.rengu.igas.momp.common.enums.MompTxnNumEnum;
import cc.rengu.igas.momp.common.enums.QueryRoleEnum;
import cc.rengu.igas.momp.common.enums.QueryTypeEnum;
import cc.rengu.igas.momp.common.enums.RespCodeEnum;
import cc.rengu.igas.momp.facade.bean.PostPaymentAvailableCouponMcInfoBean;
import cc.rengu.igas.momp.facade.request.QueryAvailableDiscountInfoAfterPaymentRequest;
import cc.rengu.igas.momp.facade.response.QueryAvailableDiscountInfoAfterPaymentResponse;
import cc.rengu.jradp.mods.dbs.Database;
import cc.rengu.oltp.service.base.RadpService;
import cc.rengu.oltp.service.common.constant.AppConfigConstant;
import cc.rengu.oltp.service.common.constant.AppParamConstant;
import cc.rengu.oltp.service.common.constant.TreeNodeConstant;
import cc.rengu.oltp.service.common.entity.BinInfo;
import cc.rengu.oltp.service.common.enums.ChannelEnum;
import cc.rengu.oltp.service.common.enums.OltpRpcdEnum;
import cc.rengu.oltp.service.model.BizException;
import cc.rengu.oltp.service.model.BizResponse;
import cc.rengu.oltp.service.realize.BinInfoService;
import cc.rengu.oltp.service.realize.impl.BinInfoServiceImpl;
import cc.rengu.oltp.utility.bean.PageInfo;
import cc.rengu.oltp.utility.bean.PageResult;
import cc.rengu.oltp.utility.util.ConvertUtil;
import cc.rengu.oltp.utility.util.DbsUtil;
import cc.rengu.oltp.utility.util.XmlConfigUtil;
import cc.rengu.oltp.utility.util.XmlTreeUtil;
import cc.rengu.utility.base.StringUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 支付成功可优惠信息查询接口实现
 *
 * @author Jinan Liu
 * @since 2020/4/2 17:49
 */
public class PostPaymentAvailableDiscountInfoQueryService extends RadpService {

    /**
     * 法人机构号
     */
    private String globalInstId;
    /**
     * 渠道交易日期
     */
    private String globalTxnDate;
    /**
     * 渠道交易时间
     */
    private String globalTxnTime;
    /**
     * 用户ID
     */
    private String globalUserId;
    /**
     * 原系统标识
     */
    private String globalsSrcSysId;
    /**
     * 流水号
     */
    private String globalTraceNo;
    /**
     * 当前交易系统时间戳
     */
    private String globalTimeStamp;
    /**
     * 业务操作流水表数据库操作实体类
     */
    List<TMTxnBizOp> tmTxnBizOpList;
    /**
     * 可领取卡券数量
     */
    private final static int COUPON_QTY = 3;
    /**
     * 手机号
     */
    private String phoneNo;
    /**
     * 银行卡号
     */
    private String cardNo;
    /**
     * 用户标志  1：未上送useId 2：单个userId 3：json字符串
     */
    private String userIdFlag;
    /**
     * 微信Id
     */
    private String wechatId;
    /**
     * 支付宝Id
     */
    private String alipayId;
    /**
     * 核心客户号
     */
    private String coreComId;

    @Override
    protected int bizInit(String s) {
        return CommonConstant.PROCESS_SUCCESS;
    }

    @Override
    protected int bizProcess(String s, int i) {

        XmlTreeUtil xmlTreeUtil = new XmlTreeUtil();

        try {

            QueryAvailableDiscountInfoAfterPaymentRequest queryAvailableDiscountInfoAfterPaymentRequest = new QueryAvailableDiscountInfoAfterPaymentRequest();
            ConvertUtil.convertOutput(queryAvailableDiscountInfoAfterPaymentRequest);

            QueryAvailableDiscountInfoAfterPaymentResponse queryAvailableDiscountInfoAfterPaymentResponse = new QueryAvailableDiscountInfoAfterPaymentResponse();
            queryAvailableDiscountInfoAfterPaymentResponse.setHeader(queryAvailableDiscountInfoAfterPaymentRequest.getHeader());
            BizResponse<QueryAvailableDiscountInfoAfterPaymentResponse> bizResponse = new BizResponse<>();
            bizResponse.setResult(queryAvailableDiscountInfoAfterPaymentResponse);

            /* 报文检查及全局变量赋值 */
            messageValidation(queryAvailableDiscountInfoAfterPaymentRequest);

            /* 服务调用 */
            BizResponse<QueryAvailableDiscountInfoAfterPaymentResponse> bizResponseNew = queryAvailableDiscountInfoAfterPayment(xmlTreeUtil, queryAvailableDiscountInfoAfterPaymentRequest, queryAvailableDiscountInfoAfterPaymentResponse);

            ConvertUtil.convertInput(bizResponseNew.getResult());

        } catch (BizException e) {
            try {
                xmlTreeUtil.setXmlTreeStringValue(TreeNodeConstant.RESP_CODE, e.getCode());
                xmlTreeUtil.setXmlTreeStringValue(TreeNodeConstant.RESP_DESC, e.getMessage());
                xmlTreeUtil.setXmlTreeStringValue(CommonConstant.KEY_RESPDESC, e.getMessage());
            } catch (Exception e1) {
                rglog.error(StringUtil.ExceptionToString(e1));
            }
        } catch (Exception e) {
            rglog.error(StringUtil.ExceptionToString(e));
            try {
                xmlTreeUtil.setXmlTreeStringValue(TreeNodeConstant.RESP_CODE, OltpRpcdEnum.OLTP_PROCESS_ERROR.getRespCode());
                xmlTreeUtil.setXmlTreeStringValue(TreeNodeConstant.RESP_DESC, OltpRpcdEnum.OLTP_PROCESS_ERROR.getRespDesc());
                xmlTreeUtil.setXmlTreeStringValue(CommonConstant.KEY_RESPDESC, e.getMessage());
            } catch (Exception e1) {
                rglog.error(StringUtil.ExceptionToString(e1));
            }
        }

        return CommonConstant.PROCESS_SUCCESS;
    }

    @Override
    protected int bizTerminate(String s) {
        return CommonConstant.PROCESS_SUCCESS;
    }

    /**
     * 支付前对客类可优惠信息查询
     *
     * @param xmlTreeUtil                                    内部XML树
     * @param queryAvailableDiscountInfoAfterPaymentRequest  支付成功可优惠信息查询接口请求对象
     * @param queryAvailableDiscountInfoAfterPaymentResponse 支付成功可优惠信息查询接口应答对象
     * @return cc.rengu.oltp.service.model.BizResponse<cc.rengu.igas.momp.facade.response.QueryAvailableDiscountInfoAfterPaymentResponse> 支付成功可优惠信息查询接口应答对象
     * @throws Exception 异常信息
     * @author Jinan Liu
     * @since 2020/6/2 19:22
     */
    private BizResponse<QueryAvailableDiscountInfoAfterPaymentResponse> queryAvailableDiscountInfoAfterPayment(XmlTreeUtil xmlTreeUtil, QueryAvailableDiscountInfoAfterPaymentRequest queryAvailableDiscountInfoAfterPaymentRequest, QueryAvailableDiscountInfoAfterPaymentResponse queryAvailableDiscountInfoAfterPaymentResponse) throws Exception {

        BizResponse<QueryAvailableDiscountInfoAfterPaymentResponse> bizResponse = new BizResponse<>();
        if (!userIdFlag.equals(CommonConstant.ONE_COMMON_CONSTANT)) {
            /* 查询用户可领取卡券信息 */
            List<PostPaymentAvailableCouponMcInfoBean> postPaymentAvailableCouponMcInfoBeanList = processCouponProcedure(queryAvailableDiscountInfoAfterPaymentRequest);
            if (null == postPaymentAvailableCouponMcInfoBeanList || postPaymentAvailableCouponMcInfoBeanList.isEmpty()) {
                /* 未查询到合并支付订单可用卡券信息 */
                rglog.info("机构<{}>的用户<{}>未查询到可用的卡券信息!", globalInstId, globalUserId);
            } else {
                queryAvailableDiscountInfoAfterPaymentResponse.setCouponInfoList(postPaymentAvailableCouponMcInfoBeanList);
            }
        }

        /* 登记业务操作流水表数据-曝光人数和曝光次数使用 */
        if (tmTxnBizOpList.isEmpty()) {
            /* 无业务数据待登记 */
            rglog.info("无业务流水数据待登记!");
        } else {
            //去重相同活动号的流水表信息
            tmTxnBizOpList = tmTxnBizOpList.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(TMTxnBizOp::getMcNo))), ArrayList::new));
            /* 开启数据库事务 */
            String dbPoolName = XmlConfigUtil.getXmlConfigCacheKeyValue(AppConfigConstant.DATABASE_CONF_NODE, AppConfigConstant.MOMP_POOL_NAME);
            String corporation = xmlTreeUtil.getXmlTreeStringValue(AppParamConstant.CORPORATION);
            if (null != corporation && !corporation.isEmpty()) {
                String dbPoolCashNode = corporation.trim() + AppParamConstant.DATABASE_CONF_NODE;
                dbPoolName = XmlConfigUtil.getXmlConfigCacheKeyValue(dbPoolCashNode, AppConfigConstant.MOMP_POOL_NAME);
            }
            DbsUtil dbsUtil = new DbsUtil(dbPoolName);
            dbsUtil.dbsBeginTransaction();

            try {

                TMTxnBizOpMapper tmTxnBizOpMapper = new TMTxnBizOpMapperImpl();
                int returnCode = tmTxnBizOpMapper.insertTmTxnBizOpList(tmTxnBizOpList);
                if (Database.DBS_SUCCESS != returnCode) {
                    dbsUtil.dbsEndTransaction(false);
                } else {
                    dbsUtil.dbsEndTransaction(true);
                }

            } catch (Exception e) {
                rglog.error("登记业务流水数据失败! <{}>", StringUtil.ExceptionToString(e));
                dbsUtil.dbsEndTransaction(false);
            }
        }

        bizResponse.setRspSysId(ChannelEnum.MOMP.getChannelType());
        bizResponse.setRespCode(RespCodeEnum.TRANS_SUCCESS.getRespCode());
        bizResponse.setRespDesc(RespCodeEnum.TRANS_SUCCESS.getRespDesc());

        queryAvailableDiscountInfoAfterPaymentResponse.setRespCode(RespCodeEnum.TRANS_SUCCESS.getRespCode());
        queryAvailableDiscountInfoAfterPaymentResponse.setRespDesc(RespCodeEnum.TRANS_SUCCESS.getRespDesc());
        bizResponse.setResult(queryAvailableDiscountInfoAfterPaymentResponse);

        return bizResponse;
    }

    /**
     * 查询用户可领取卡券信息
     *
     * @return java.util.List<cc.rengu.igas.momp.facade.bean.PrePaymentAvailableCouponMcInfoBean> 卡券类优惠信息对象
     * @author Jinan Liu
     * @since 2020/4/27 21:37
     */
    private List<PostPaymentAvailableCouponMcInfoBean> processCouponProcedure(QueryAvailableDiscountInfoAfterPaymentRequest queryAvailableDiscountInfoAfterPaymentRequest) {

        try {

            List<TMCouponInfo> tmCouponInfoList = claimAvailableFreeCouponForUser(queryAvailableDiscountInfoAfterPaymentRequest);
            if (null == tmCouponInfoList || tmCouponInfoList.isEmpty()) {
                /* 未查询到足够的可领取的免费券信息 */
                rglog.info("未查询到足够的可领取的免费券信息!还需继续查询!");
                return null;
            } else {
                /* 查询卡券规则信息 */
                List<TMMcCouponRuleInfo> tmMcCouponRuleInfoList = selectCouponRuleInfo(tmCouponInfoList);
                if (null == tmMcCouponRuleInfoList || tmMcCouponRuleInfoList.size() != tmCouponInfoList.size()) {
                    rglog.error("获取卡券列表对应的卡券规则列表失败!");
                    return null;
                }
            }

            /* 已取到3张卡券,可以应答渠道 */
            return tmCouponInfoList.stream().map(this::convertCouponInfo).collect(Collectors.toList());

        } catch (Exception e) {
            rglog.error(StringUtil.ExceptionToString(e));
            throw new BizException(RespCodeEnum.SYSTEM_ERROR.getRespCode(), RespCodeEnum.SYSTEM_ERROR.getRespDesc());
        }
    }


    /**
     * 领取可用免费优惠券
     *
     * @param queryAvailableDiscountInfoAfterPaymentRequest 请求对象
     * @return 卡券集合
     * @throws Exception 异常
     */
    private List<TMCouponInfo> claimAvailableFreeCouponForUser(QueryAvailableDiscountInfoAfterPaymentRequest queryAvailableDiscountInfoAfterPaymentRequest) throws Exception {
        String instId = queryAvailableDiscountInfoAfterPaymentRequest.getHeader().getInstId();
        String mchntNo = queryAvailableDiscountInfoAfterPaymentRequest.getMchntNo();
        List<TMCouponInfo> tmCouponInfoList = new ArrayList<>();
        List<TMMcMchntInfo> tmMcMchntInfoListByMchntArea = new ArrayList<>();
        List<TMMcCouponInfo> tmMcCouponInfoListByMchntNo = new ArrayList<>();
        List<TMMcCouponInfo> tmMcCouponInfoListByMchntArea = new ArrayList<>();

        // step 1 先查此商户的所有营销活动
        McMchntInfoMapper mcMchntInfoMapper = new McMchntInfoMapperImpl();
        List<TMMcMchntInfo> tmMcMchntInfoListByMchntNo = mcMchntInfoMapper.selectMcMchntInfoListByinstIdMchntNo(instId, mchntNo, null);
        // 查询该商户所属商圈的营销活动
        MchntInfoMapper mchntInfoMapper = new MchntInfoMapperImpl();
        TBMchntBaseInfo mchntBaseInfo = mchntInfoMapper.selectMchntBaseInfoByMchntNo(instId, mchntNo);
        String mchntArea = "";
        if (null != mchntBaseInfo) {
            mchntArea = mchntBaseInfo.getMchntArea();
        }
        if (!StringUtil.isNullorEmpty(mchntArea)) {
            rglog.info("该商户有商圈，可以根据商圈进行查询营销活动");
            tmMcMchntInfoListByMchntArea = mcMchntInfoMapper.selectMcMchntInfoListByinstIdMchntNo(instId, mchntArea, null);
        }

        // step 1.1 根据营销活动号查询卡券营销活动表，获取该商户可用的卡券营销活动
        McDetailInfoMapper mcDetailInfoMapper = new McDetailInfoMapperImpl();
        if (!CollectionUtils.isEmpty(tmMcMchntInfoListByMchntNo)) {
            rglog.debug("查询得到该商户有营销活动");
            for (TMMcMchntInfo tmMcMchntInfo : tmMcMchntInfoListByMchntNo) {
                TMMcCouponInfo tmMcCouponInfo = mcDetailInfoMapper.selectCouponMcDetailInfo(instId, tmMcMchntInfo.getMcNo());
                if (null != tmMcCouponInfo) {
                    tmMcCouponInfoListByMchntNo.add(tmMcCouponInfo);
                }
            }
        }
        if (!CollectionUtils.isEmpty(tmMcMchntInfoListByMchntArea)) {
            rglog.info("该商户所属商圈有营销活动");
            for (TMMcMchntInfo tmMcMchntInfo : tmMcMchntInfoListByMchntArea) {
                TMMcCouponInfo tmMcCouponInfo = mcDetailInfoMapper.selectCouponMcDetailInfo(instId, tmMcMchntInfo.getMcNo());
                if (null != tmMcCouponInfo) {
                    tmMcCouponInfoListByMchntArea.add(tmMcCouponInfo);
                }
            }
        }

        if (!CollectionUtils.isEmpty(tmMcCouponInfoListByMchntNo)) {
            // step 2 根据商户营销活动去与查询出来的指定用户测试营销活动比较，获取3张卡券，够三张返回，不够的话继续
            List<TMCouponInfo> tmCouponInfoListByMchntNoWithUser = getFreeTestCouponWithUserWhiteListAndMchntNo(COUPON_QTY, tmMcCouponInfoListByMchntNo);
            if (!CollectionUtils.isEmpty(tmCouponInfoListByMchntNoWithUser)) {
                tmCouponInfoList.addAll(tmCouponInfoListByMchntNoWithUser);
            }
        }

        if (null == tmCouponInfoList || tmCouponInfoList.isEmpty() || COUPON_QTY > tmCouponInfoList.size()) {
            rglog.info("该商户与该用户测试营销活动卡券不足三张，继续查询其他可用免费券信息");
            int getQty;
            /* 不足3张卡券,继续查询所有人均可领取的免费券的信息 */
            if (null != tmCouponInfoList && !tmCouponInfoList.isEmpty()) {
                getQty = tmCouponInfoList.size();
            } else {
                getQty = CommonConstant.ZERO;
            }

            if (!CollectionUtils.isEmpty(tmMcCouponInfoListByMchntNo)) {
                // step 3 根据商户营销活动去与查询出来的指定用户营销活动比较，获取3张卡券，够三张返回，不够的话继续
                /* 取用户可领取的限定了用户白名单的卡券营销活动的卡券 */
                rglog.info("取用户可领取的限定了用户白名单的卡券营销活动的卡券");
                List<TMCouponInfo> tmCouponInfoListByMchntNoWithUser1 = getFreeCouponWithUserWhiteListAndMchntNo(COUPON_QTY - getQty, tmMcCouponInfoListByMchntNo);
                if (!CollectionUtils.isEmpty(tmCouponInfoListByMchntNoWithUser1)) {

                    tmCouponInfoList.addAll(tmCouponInfoListByMchntNoWithUser1);
                    //过滤出重复的
                    rglog.debug("去重前卡券集合<{}>", JSONObject.toJSONString(tmCouponInfoList));
                    tmCouponInfoList = tmCouponInfoList.stream().distinct().collect(Collectors.toList());
                    rglog.debug("去重后卡券集合<{}>", JSONObject.toJSONString(tmCouponInfoList));
                }
            }
            // 校验卡券数量，判断是返回还是继续
            if (CollectionUtils.isEmpty(tmCouponInfoList) || COUPON_QTY > tmCouponInfoList.size()) {
                rglog.info("取用户可领取的限定了用户白名单的卡券营销活动的卡券不足三张，继续获取");
                // step 4 根据商户营销活动去查不指定用户，所有用户均可使用的营销活动，获取3张卡券
                if (null != tmCouponInfoList && tmCouponInfoList.size() > 0) {
                    getQty = tmCouponInfoList.size();
                }
                if (!CollectionUtils.isEmpty(tmMcCouponInfoListByMchntNo)) {
                    /* 取用户可领取的未限定用户白名单的卡券营销活动的卡券 */
                    rglog.info("取用户可领取的未限定用户白名单的卡券营销活动的卡券");
                    List<TMCouponInfo> tmCouponInfoListByMchntNoWithUser2 = getFreeCouponWithouUserWhiteListAndMchntNo(COUPON_QTY - getQty, tmMcCouponInfoListByMchntNo);
                    if (!CollectionUtils.isEmpty(tmCouponInfoListByMchntNoWithUser2)) {
                        tmCouponInfoList.addAll(tmCouponInfoListByMchntNoWithUser2);
                        //过滤出重复的
                        rglog.debug("去重前卡券集合<{}>", JSONObject.toJSONString(tmCouponInfoList));
                        tmCouponInfoList = tmCouponInfoList.stream().distinct().collect(Collectors.toList());
                        rglog.debug("去重后卡券集合<{}>", JSONObject.toJSONString(tmCouponInfoList));
                    }
                }
                // 校验卡券数量，判断是返回还是继续
                if (CollectionUtils.isEmpty(tmCouponInfoList) || COUPON_QTY > tmCouponInfoList.size()) {
                    rglog.info("取用户可领取的未限定用户白名单的卡券营销活动的卡券不足三张，继续获取");
                    if (null != tmCouponInfoList && tmCouponInfoList.size() > 0) {
                        getQty = tmCouponInfoList.size();
                    }
                    if (!CollectionUtils.isEmpty(tmMcCouponInfoListByMchntArea)) {
                        // step 6 根据商圈营销活动去查询指定用户测试营销活动，获取3张卡券
                        rglog.info("根据商圈营销活动去查询指定用户测试营销活动");
                        List<TMCouponInfo> tmCouponInfoListByMchntAreaWithUser = getFreeTestCouponWithUserWhiteListAndMchntNo(COUPON_QTY - getQty, tmMcCouponInfoListByMchntArea);
                        if (null != tmCouponInfoListByMchntAreaWithUser && tmCouponInfoListByMchntAreaWithUser.size() > 0) {
                            tmCouponInfoList.addAll(tmCouponInfoListByMchntAreaWithUser);
                            //过滤出重复的
                            rglog.debug("去重前卡券集合<{}>", JSONObject.toJSONString(tmCouponInfoList));
                            tmCouponInfoList = tmCouponInfoList.stream().distinct().collect(Collectors.toList());
                            rglog.debug("去重后卡券集合<{}>", JSONObject.toJSONString(tmCouponInfoList));
                        }
                    }
                    if (CollectionUtils.isEmpty(tmCouponInfoList) || COUPON_QTY > tmCouponInfoList.size()) {
                        rglog.info("根据商圈营销活动去查询指定用户测试营销活动不足三张，继续获取");
                        if (null != tmCouponInfoList && tmCouponInfoList.size() > 0) {
                            getQty = tmCouponInfoList.size();
                        }
                        if (!CollectionUtils.isEmpty(tmMcCouponInfoListByMchntArea)) {
                            // step 7 根据商圈营销活动去查询指定用户营销活动，获取3张卡券
                            rglog.info("根据商圈营销活动去查询指定用户营销活动");
                            List<TMCouponInfo> freeCouponWithUserWhiteListAndMchntArea = getFreeCouponWithUserWhiteListAndMchntNo(COUPON_QTY - getQty, tmMcCouponInfoListByMchntArea);
                            if (null != freeCouponWithUserWhiteListAndMchntArea && freeCouponWithUserWhiteListAndMchntArea.size() > 0) {
                                tmCouponInfoList.addAll(freeCouponWithUserWhiteListAndMchntArea);
                                //过滤出重复的
                                rglog.debug("去重前卡券集合<{}>", JSONObject.toJSONString(tmCouponInfoList));
                                tmCouponInfoList = tmCouponInfoList.stream().distinct().collect(Collectors.toList());
                                rglog.debug("去重后卡券集合<{}>", JSONObject.toJSONString(tmCouponInfoList));
                            }
                        }
                        if (CollectionUtils.isEmpty(tmCouponInfoList) || COUPON_QTY > tmCouponInfoList.size()) {
                            if (null != tmCouponInfoList && tmCouponInfoList.size() > 0) {
                                getQty = tmCouponInfoList.size();
                            }
                            if (!CollectionUtils.isEmpty(tmMcCouponInfoListByMchntArea)) {
                                // step 8 根据商圈营销活动去查不指定用户，所有用户均可使用的营销活动，获取3张卡券
                                List<TMCouponInfo> freeCouponWithouUserWhiteListAndMchntArea = getFreeCouponWithouUserWhiteListAndMchntNo(COUPON_QTY - getQty, tmMcCouponInfoListByMchntArea);
                                if (null != freeCouponWithouUserWhiteListAndMchntArea && freeCouponWithouUserWhiteListAndMchntArea.size() > 0) {
                                    tmCouponInfoList.addAll(freeCouponWithouUserWhiteListAndMchntArea);
                                    //过滤出重复的
                                    rglog.debug("去重前卡券集合<{}>", JSONObject.toJSONString(tmCouponInfoList));
                                    tmCouponInfoList = tmCouponInfoList.stream().distinct().collect(Collectors.toList());
                                    rglog.debug("去重后卡券集合<{}>", JSONObject.toJSONString(tmCouponInfoList));
                                }
                            }
                            if (CollectionUtils.isEmpty(tmCouponInfoList) || COUPON_QTY > tmCouponInfoList.size()) {
                                if (null != tmCouponInfoList && tmCouponInfoList.size() > 0) {
                                    getQty = tmCouponInfoList.size();
                                }
                                // step 9.1 按照原有逻辑，查询出三张
                                List<TMCouponInfo> testFreeCouponWithUserWhiteList = getTestFreeCouponWithUserWhiteList(COUPON_QTY - getQty);
                                if (!CollectionUtils.isEmpty(testFreeCouponWithUserWhiteList)) {
                                    tmCouponInfoList.addAll(testFreeCouponWithUserWhiteList);
                                    //过滤出重复的
                                    rglog.debug("去重前卡券集合<{}>", JSONObject.toJSONString(tmCouponInfoList));
                                    tmCouponInfoList = tmCouponInfoList.stream().distinct().collect(Collectors.toList());
                                    rglog.debug("去重后卡券集合<{}>", JSONObject.toJSONString(tmCouponInfoList));
                                }
                                if (CollectionUtils.isEmpty(tmCouponInfoList) || COUPON_QTY > tmCouponInfoList.size()) {
                                    if (null != tmCouponInfoList && tmCouponInfoList.size() > 0) {
                                        getQty = tmCouponInfoList.size();
                                    }
                                    // step 9.2 按照原有逻辑，查询出三张
                                    List<TMCouponInfo> freeCouponWithUserWhiteList = getFreeCouponWithUserWhiteList(COUPON_QTY - getQty);
                                    List<TMCouponInfo> newTmCouponInfoList = new ArrayList<>();
                                    if (null != freeCouponWithUserWhiteList && freeCouponWithUserWhiteList.size() > 0 && null != tmCouponInfoList) {
                                        tmCouponInfoList.addAll(freeCouponWithUserWhiteList);
                                        //过滤出重复的
                                        rglog.debug("去重前卡券集合<{}>", JSONObject.toJSONString(tmCouponInfoList));
                                        tmCouponInfoList = tmCouponInfoList.stream().distinct().collect(Collectors.toList());
                                        rglog.debug("去重后卡券集合<{}>", JSONObject.toJSONString(tmCouponInfoList));
                                        newTmCouponInfoList.addAll(tmCouponInfoList);
                                    }

                                    if (CollectionUtils.isEmpty(newTmCouponInfoList) || COUPON_QTY > newTmCouponInfoList.size()) {
                                        if (null != newTmCouponInfoList && newTmCouponInfoList.size() > 0) {
                                            getQty = newTmCouponInfoList.size();
                                        }
                                        if (0 == newTmCouponInfoList.size()) {
                                            if (null != tmCouponInfoList && tmCouponInfoList.size() > 0) {
                                                getQty = tmCouponInfoList.size();
                                            }
                                        }
                                        List<TMCouponInfo> twoTmCouponInfoList = new ArrayList<>();
                                        if (!CollectionUtils.isEmpty(newTmCouponInfoList)) {
                                            twoTmCouponInfoList.addAll(newTmCouponInfoList);
                                        } else if (!CollectionUtils.isEmpty(tmCouponInfoList)) {
                                            twoTmCouponInfoList.addAll(tmCouponInfoList);
                                        } else {

                                        }

                                        // step 9.3 按照原有逻辑，最后一步
                                        List<TMCouponInfo> freeCouponWithouUserWhiteList = getFreeCouponWithouUserWhiteList(COUPON_QTY - getQty, twoTmCouponInfoList);
                                        if (null == freeCouponWithouUserWhiteList || freeCouponWithouUserWhiteList.isEmpty()) {
                                            /* 未取到未限定用户的卡券信息,如果已取到已限定用户的数据,则直接返回,否则返回null */
                                            return null;
                                        } else {
                                            /* 已取到未限定用户的卡券信息,最多返回3张卡券的信息 */
                                            if (COUPON_QTY > freeCouponWithouUserWhiteList.size()) {
                                                return freeCouponWithouUserWhiteList;
                                            } else {
                                                return freeCouponWithouUserWhiteList.subList(0, COUPON_QTY);
                                            }
                                        }

                                    } else if (COUPON_QTY < newTmCouponInfoList.size()) {
                                        return newTmCouponInfoList.subList(CommonConstant.ZERO, COUPON_QTY);
                                    } else {
                                        return newTmCouponInfoList;
                                    }

                                } else if (COUPON_QTY < tmCouponInfoList.size()) {
                                    return tmCouponInfoList.subList(CommonConstant.ZERO, COUPON_QTY);
                                } else {
                                    return tmCouponInfoList;
                                }

                            } else if (COUPON_QTY < tmCouponInfoList.size()) {
                                return tmCouponInfoList.subList(CommonConstant.ZERO, COUPON_QTY);
                            } else {
                                return tmCouponInfoList;
                            }

                        } else if (COUPON_QTY < tmCouponInfoList.size()) {
                            return tmCouponInfoList.subList(CommonConstant.ZERO, COUPON_QTY);
                        } else {
                            return tmCouponInfoList;
                        }

                    } else if (COUPON_QTY < tmCouponInfoList.size()) {
                        rglog.info("根据商圈营销活动去查询指定用户测试营销活动的卡券已有三张，返回卡券信息");
                        return tmCouponInfoList.subList(CommonConstant.ZERO, COUPON_QTY);
                    } else {
                        rglog.info("根据商圈营销活动去查询指定用户测试营销活动的卡券已有三张，返回卡券信息");
                        return tmCouponInfoList;
                    }

                } else if (COUPON_QTY < tmCouponInfoList.size()) {
                    rglog.info("取用户可领取的未限定用户白名单的卡券营销活动的卡券已有三张，返回卡券信息");
                    return tmCouponInfoList.subList(CommonConstant.ZERO, COUPON_QTY);
                } else {
                    rglog.info("取用户可领取的未限定用户白名单的卡券营销活动的卡券已有三张，返回卡券信息");
                    return tmCouponInfoList;
                }

            } else if (COUPON_QTY < tmCouponInfoList.size()) {
                rglog.info("取用户可领取的限定了用户白名单的卡券营销活动的卡券已有三张，返回卡券信息");
                return tmCouponInfoList.subList(CommonConstant.ZERO, COUPON_QTY);
            } else {
                rglog.info("取用户可领取的限定了用户白名单的卡券营销活动的卡券已有三张，返回卡券信息");
                return tmCouponInfoList;
            }

        } else if (COUPON_QTY < tmCouponInfoList.size()) {
            /* 已有至少3张卡券,直接返回,最多返回3张卡券信息 */
            rglog.info("该商户与该用户测试营销活动卡券已有三张，返回卡券信息");
            return tmCouponInfoList.subList(CommonConstant.ZERO, COUPON_QTY);
        } else {
            /* 已有3张卡券,直接返回 */
            rglog.info("该商户与该用户测试营销活动卡券已有三张，返回卡券信息");
            return tmCouponInfoList;
        }

    }

    /**
     * 根据商户号 获取卡券
     *
     * @param couponQty
     * @param tmMcCouponInfoListByMchntNo
     * @return
     * @throws Exception
     */
    private List<TMCouponInfo> getFreeCouponWithouUserWhiteListAndMchntNo(int couponQty, List<TMMcCouponInfo> tmMcCouponInfoListByMchntNo) throws Exception {
        int pageIndex = CommonConstant.ZERO;

        PageInfo pageInfo = new PageInfo();
        pageInfo.setPageIndex(pageIndex);
        pageInfo.setPageSize(couponQty);

        PageResult pageResult;

        CpMcListInfoInObj cpMcListInfoInObj = new CpMcListInfoInObj();
        cpMcListInfoInObj.setInstId(globalInstId);
        cpMcListInfoInObj.setTxnDate(globalTxnDate);

        McDetailInfoMapper mcDetailInfoMapper = new McDetailInfoMapperImpl();

        List<TMCouponInfo> tmCouponInfoList = new ArrayList<>();


        while (couponQty >= tmCouponInfoList.size()) {

            /* 查询未限制用户白名单中的免费券的卡券类营销活动 */
            pageResult = mcDetailInfoMapper.selectCouponMcInfoWithoutUserWhiteList(cpMcListInfoInObj, pageInfo);
            if (null == pageResult || null == pageResult.getPageInfo() || null == pageResult.getResult()) {
                rglog.error("未取到法人机构号<{}>的用户<{}>可参加的未限制用户白名单的卡券营销活动信息!", globalInstId, globalUserId);
                return null;
            }

            int totalPage = pageResult.getPageInfo().getTotalPage();
            if (CommonConstant.ZERO == totalPage) {
                return null;
            }

            rglog.info("取出<{}>个当前用户<{}>可参与的未限制用户白名单的卡券营销活动", pageResult.getResult().size(), globalUserId);

            List<TMMcCouponInfo> tmMcCouponInfoList = pageResult.getResult().stream().map(object -> (TMMcCouponInfo) object).collect(Collectors.toList());

            rglog.debug("卡券信息<{}>", JSONObject.toJSONString(tmMcCouponInfoList));
            List<TMMcCouponInfo> newTmMcCouponInfoList = new ArrayList<>();
            for (TMMcCouponInfo tmMcCouponInfo : tmMcCouponInfoListByMchntNo) {
                List<TMMcCouponInfo> tmMcCouponInfos = tmMcCouponInfoList.stream().filter(item -> tmMcCouponInfo.getMcNo().equals(item.getMcNo())).collect(Collectors.toList());
                if (!CollectionUtils.isEmpty(tmMcCouponInfos)) {
                    newTmMcCouponInfoList.addAll(tmMcCouponInfos);
                }
            }
            rglog.debug("商户营销活动与营销活动中的活动共同集合<{}>", JSONObject.toJSONString(newTmMcCouponInfoList));
            List<TMCouponInfo> tmCouponInfoList1 = new ArrayList<>();
            if (!CollectionUtils.isEmpty(newTmMcCouponInfoList)) {
                /* 取对应卡券营销活动的可领取卡券,每个营销活动只取一张卡券 */
                tmCouponInfoList1 = selectAvailableCouponInfo(newTmMcCouponInfoList);
            }

            //如果取到的卡券不为null，则添加到卡券信息列表
            if (null != tmCouponInfoList1 && !tmCouponInfoList1.isEmpty()) {
                tmCouponInfoList.addAll(tmCouponInfoList1);
                rglog.debug("去重前卡券集合<{}>", JSONObject.toJSONString(tmCouponInfoList));
                tmCouponInfoList = tmCouponInfoList.stream().distinct().collect(Collectors.toList());
                rglog.debug("去重前卡券集合<{}>", JSONObject.toJSONString(tmCouponInfoList));
            }

            /* 如果获取到couponQty张卡券,则返回退出循环并返回,如果未领取到足够卡券,则继续流程 */
            if (couponQty <= tmCouponInfoList.size()) {
                return tmCouponInfoList;
            } else {
                pageIndex = pageIndex + CommonConstant.ONE;
                pageInfo.setPageIndex(pageIndex);

                if (pageIndex >= totalPage) {
                    /* 已查询到最后一页,如果已取到数据,按取到的数据返回,如果无数据,返回null */
                    if (tmCouponInfoList.isEmpty()) {
                        rglog.info("未获取到可领取的用户在白名单中的免费卡券信息!");
                        return null;
                    } else {
                        return tmCouponInfoList;
                    }
                }
            }
        }

        return null;
    }


    /**
     * 取用户可领取的限定了用户白名单的卡券营销活动的卡券
     *
     * @param couponQty                   还需获取卡券数量
     * @param tmMcCouponInfoListByMchntNo 商户营销集合
     * @return 卡券信息
     */
    private List<TMCouponInfo> getFreeCouponWithUserWhiteListAndMchntNo(int couponQty, List<TMMcCouponInfo> tmMcCouponInfoListByMchntNo) throws Exception {
        int pageIndex = CommonConstant.ZERO;

        PageInfo pageInfo = new PageInfo();
        pageInfo.setPageIndex(pageIndex);
        pageInfo.setPageSize(couponQty);

        PageResult pageResult;

        CpMcListInfoInObj cpMcListInfoInObj = new CpMcListInfoInObj();
        cpMcListInfoInObj.setInstId(globalInstId);
        cpMcListInfoInObj.setAcctNo(globalUserId);
        cpMcListInfoInObj.setTxnDate(globalTxnDate);
        McDetailInfoMapper mcDetailInfoMapper = new McDetailInfoMapperImpl();

        List<TMCouponInfo> tmCouponInfoList = new ArrayList<>();


        while (couponQty >= tmCouponInfoList.size()) {

            /* 查询用户在白名单中的免费券的卡券类营销活动 */
            pageResult = mcDetailInfoMapper.selectCouponMcInfoUsingUserWhiteList(cpMcListInfoInObj, pageInfo);
            if (null == pageResult || null == pageResult.getPageInfo() || null == pageResult.getResult()) {
                rglog.error("未取到法人机构号<{}>的用户<{}>可参加的限制用户白名单（活动配置了用户）的免费卡券营销活动信息!", globalInstId, globalUserId);
                return null;
            }

            int totalPage = pageResult.getPageInfo().getTotalPage();
            if (CommonConstant.ZERO == totalPage) {
                return null;
            }

            List<TMMcCouponInfo> tmMcCouponInfoList = pageResult.getResult().stream().map(object -> (TMMcCouponInfo) object).collect(Collectors.toList());
            List<TMMcCouponInfo> newTmMcCouponInfoList = new ArrayList<>();
            for (TMMcCouponInfo tmMcCouponInfo : tmMcCouponInfoListByMchntNo) {
                List<TMMcCouponInfo> tmMcCouponInfos = tmMcCouponInfoList.stream().filter(item -> tmMcCouponInfo.getMcNo().equals(item.getMcNo())).collect(Collectors.toList());
                if (!CollectionUtils.isEmpty(tmMcCouponInfos)) {
                    newTmMcCouponInfoList.addAll(tmMcCouponInfos);
                }
            }
            rglog.debug("商户营销活动与营销活动中的活动共同集合<{}>", JSONObject.toJSONString(newTmMcCouponInfoList));
            List<TMCouponInfo> tmCouponInfoList1 = new ArrayList<>();
            if (!CollectionUtils.isEmpty(newTmMcCouponInfoList)) {
                /* 取对应卡券营销活动的可领取卡券,每个营销活动只取一张卡券 */
                tmCouponInfoList1 = selectAvailableCouponInfo(newTmMcCouponInfoList);
            }
            //如果取到的卡券不为null，则添加到卡券信息列表
            if (null != tmCouponInfoList1 && !tmCouponInfoList1.isEmpty()) {
                tmCouponInfoList.addAll(tmCouponInfoList1);
                rglog.debug("去重前卡券集合<{}>", JSONObject.toJSONString(tmCouponInfoList));
                tmCouponInfoList = tmCouponInfoList.stream().distinct().collect(Collectors.toList());
                rglog.debug("去重后卡券集合<{}>", JSONObject.toJSONString(tmCouponInfoList));
            }

            /* 如果获取到3张卡券,则返回退出循环并返回,如果未领取到足够卡券,则继续流程 */
            if (couponQty <= tmCouponInfoList.size()) {
                return tmCouponInfoList;
            } else {
                pageIndex = pageIndex + CommonConstant.ONE;
                pageInfo.setPageIndex(pageIndex);

                if (pageIndex >= totalPage) {
                    /* 已查询到最后一页,如果已取到数据,按取到的数据返回,如果无数据,返回null */
                    if (tmCouponInfoList.isEmpty()) {
                        rglog.info("未获取到可领取的用户在白名单中的免费卡券信息!");
                        return null;
                    } else {
                        return tmCouponInfoList;
                    }
                }
            }
        }

        return null;
    }

    /**
     * 根据商户号和置顶用户获取卡券信息
     *
     * @param tmMcCouponInfoListByMchntNo 根据商户查询得出的卡券营销信息
     * @return 卡券信息
     */
    private List<TMCouponInfo> getFreeTestCouponWithUserWhiteListAndMchntNo(int couponQty, List<TMMcCouponInfo> tmMcCouponInfoListByMchntNo) throws Exception {

        int pageIndex = CommonConstant.ZERO;

        PageInfo pageInfo = new PageInfo();
        pageInfo.setPageIndex(pageIndex);
        pageInfo.setPageSize(couponQty);

        PageResult pageResult;

        CpMcListInfoInObj cpMcListInfoInObj = new CpMcListInfoInObj();
        cpMcListInfoInObj.setInstId(globalInstId);
        cpMcListInfoInObj.setAcctNo(globalUserId);
        cpMcListInfoInObj.setTxnDate(globalTxnDate);

        McDetailInfoMapper mcDetailInfoMapper = new McDetailInfoMapperImpl();

        List<TMCouponInfo> tmCouponInfoList = new ArrayList<>();

        while (couponQty >= tmCouponInfoList.size()) {

            /* 查询用户在白名单中的免费券的卡券类营销活动 */
            pageResult = mcDetailInfoMapper.selectTestCouponMcInfoWithoutUserWhiteList(cpMcListInfoInObj, pageInfo);
            if (null == pageResult || null == pageResult.getPageInfo() || null == pageResult.getResult()) {
                rglog.error("未取到法人机构号<{}>的用户<{}>可参加的限制用户白名单（活动配置了用户）的测试中的免费卡券营销活动信息!", globalInstId, globalUserId);
                return null;
            }

            //获取总页数
            int totalPage = pageResult.getPageInfo().getTotalPage();
            if (CommonConstant.ZERO == totalPage) {
                return null;
            }
            List<TMMcCouponInfo> tmMcCouponInfoList = pageResult.getResult().stream().map(object -> (TMMcCouponInfo) object).collect(Collectors.toList());
            //判断 tmMcCouponInfoList 的营销编号和根据商户号查出来的是否一致
            List<TMMcCouponInfo> newTmMcCouponInfoList = new ArrayList<>();
            for (TMMcCouponInfo tmMcCouponInfo : tmMcCouponInfoListByMchntNo) {
                List<TMMcCouponInfo> tmMcCouponInfos = tmMcCouponInfoList.stream().filter(item -> tmMcCouponInfo.getMcNo().equals(item.getMcNo())).collect(Collectors.toList());
                if (!CollectionUtils.isEmpty(tmMcCouponInfos)) {
                    newTmMcCouponInfoList.addAll(tmMcCouponInfos);
                }
            }
            rglog.debug("商户营销活动与营销活动中的活动共同集合<{}>", JSONObject.toJSONString(newTmMcCouponInfoList));
            List<TMCouponInfo> tmCouponInfoList1 = new ArrayList<>();
            if (!CollectionUtils.isEmpty(newTmMcCouponInfoList)) {

                /* 取对应卡券营销活动的可领取卡券,每个营销活动只取一张卡券 */
                tmCouponInfoList1 = selectAvailableCouponInfo(newTmMcCouponInfoList);
            }

            //如果取到的卡券不为null，则添加到卡券信息列表
            if (null != tmCouponInfoList1 && !tmCouponInfoList1.isEmpty()) {
                tmCouponInfoList.addAll(tmCouponInfoList1);
                rglog.debug("去重前卡券集合<{}>", JSONObject.toJSONString(tmCouponInfoList));
                tmCouponInfoList = tmCouponInfoList.stream().distinct().collect(Collectors.toList());
                rglog.debug("去重后卡券集合<{}>", JSONObject.toJSONString(tmCouponInfoList));
            }

            /* 如果获取到3张卡券,则返回退出循环并返回,如果未领取到足够卡券,则继续流程 */
            if (couponQty <= tmCouponInfoList.size()) {
                return tmCouponInfoList;
            } else {
                pageIndex = pageIndex + CommonConstant.ONE;
                pageInfo.setPageIndex(pageIndex);

                if (pageIndex >= totalPage) {
                    /* 已查询到最后一页,如果已取到数据,按取到的数据返回,如果无数据,返回null */
                    if (tmCouponInfoList.isEmpty()) {
                        rglog.info("未获取到可领取的用户在白名单中的测试中的免费卡券信息!");
                        return null;
                    } else {
                        return tmCouponInfoList;
                    }
                }
            }
        }

        return null;
    }

    /*
     *//**
     * 领取可用免费卡券
     *
     * @author Jinan Liu
     * @since 2020/6/8 11:33
     * @return java.util.List<cc.rengu.igas.momp.common.entity.TMCouponInfo> 卡券信息表
     * @throws Exception 异常信息
     *//*
    private List<TMCouponInfo>  claimAvailableFreeCouponForUser() throws Exception {

        List<TMCouponInfo> tmCouponInfoList = new ArrayList<>();

        *//* 取用户可领取的限定了用户白名单的测试中的卡券营销活动的卡券 *//*
        List<TMCouponInfo> tmCouponInfoList3 = getTestFreeCouponWithUserWhiteList();
        if (null == tmCouponInfoList3 || tmCouponInfoList3.isEmpty() || COUPON_QTY > tmCouponInfoList3.size()) {
            int getQty;

            *//* 不足3张卡券,继续查询所有人均可领取的免费券的信息 *//*
            if (null != tmCouponInfoList3 && !tmCouponInfoList3.isEmpty()) {
                tmCouponInfoList.addAll(tmCouponInfoList3);
                getQty = tmCouponInfoList.size();
            } else {
                getQty = CommonConstant.ZERO;
            }

            *//* 取用户可领取的限定了用户白名单的卡券营销活动的卡券 *//*
            List<TMCouponInfo> tmCouponInfoList1 = getFreeCouponWithUserWhiteList(COUPON_QTY - getQty);
            if (null == tmCouponInfoList1 || tmCouponInfoList1.isEmpty() || (COUPON_QTY - getQty) > tmCouponInfoList1.size()) {
                if (null != tmCouponInfoList1 && tmCouponInfoList1.size()>0){
                    tmCouponInfoList.addAll(tmCouponInfoList1);
                    getQty = tmCouponInfoList.size();
                }
                *//* 取用户可领取的未限定用户白名单的卡券营销活动的卡券 *//*
                List<TMCouponInfo> tmCouponInfoList2 = getFreeCouponWithouUserWhiteList(COUPON_QTY - getQty);
                if (null == tmCouponInfoList2 || tmCouponInfoList2.isEmpty()) {
                    *//* 未取到未限定用户的卡券信息,如果已取到已限定用户的数据,则直接返回,否则返回null *//*
                    if (CommonConstant.ZERO == getQty) {
                        return null;
                    } else {
                        return tmCouponInfoList;
                    }
                } else {
                    *//* 已取到未限定用户的卡券信息,最多返回3张卡券的信息 *//*
                    tmCouponInfoList.addAll(tmCouponInfoList2);
                    if (COUPON_QTY > tmCouponInfoList.size()) {
                        return tmCouponInfoList;
                    } else {
                        return tmCouponInfoList.subList(0, COUPON_QTY);
                    }
                }
            }else{
                *//* 已取到未限定用户的卡券信息,最多返回3张卡券的信息 *//*
                tmCouponInfoList.addAll(tmCouponInfoList1);
                if (COUPON_QTY > tmCouponInfoList.size()) {
                    return tmCouponInfoList;
                } else {
                    return tmCouponInfoList.subList(0, COUPON_QTY);
                }
            }
        } else if (COUPON_QTY < tmCouponInfoList3.size()) {
            *//* 已有至少3张卡券,直接返回,最多返回3张卡券信息 *//*
            return tmCouponInfoList3.subList(CommonConstant.ZERO, COUPON_QTY);
        } else {
            *//* 已有3张卡券,直接返回 *//*
            return tmCouponInfoList3;
        }
    }*/

    /**
     * 取用户可领取的限定了用户白名单的卡券营销活动的卡券
     * 最多返回3条数据
     * 如果未取到数据,返回空
     *
     * @return java.util.List<cc.rengu.igas.momp.common.entity.TMCouponInfo> 卡券信息表
     * @throws Exception 异常信息
     * @author Jinan Liu
     * @since 2020/6/8 17:55
     */
    private List<TMCouponInfo> getFreeCouponWithUserWhiteList(int couponQty) throws Exception {

        int pageIndex = CommonConstant.ZERO;

        PageInfo pageInfo = new PageInfo();
        pageInfo.setPageIndex(pageIndex);
        pageInfo.setPageSize(couponQty);

        PageResult pageResult;

        CpMcListInfoInObj cpMcListInfoInObj = new CpMcListInfoInObj();
        cpMcListInfoInObj.setInstId(globalInstId);
        //如果上送卡号 需查询卡bin
        globalUserId = getCardBin(globalUserId);
        cpMcListInfoInObj.setAcctNo(globalUserId);
        cpMcListInfoInObj.setTxnDate(globalTxnDate);
        McDetailInfoMapper mcDetailInfoMapper = new McDetailInfoMapperImpl();

        List<TMCouponInfo> tmCouponInfoList = new ArrayList<>();

        while (couponQty >= tmCouponInfoList.size()) {

            /* 查询用户在白名单中的免费券的卡券类营销活动 */
            pageResult = mcDetailInfoMapper.selectCouponMcInfoUsingUserWhiteList(cpMcListInfoInObj, pageInfo);
            if (null == pageResult || null == pageResult.getPageInfo() || null == pageResult.getResult()) {
                rglog.error("未取到法人机构号<{}>的用户<{}>可参加的限制用户白名单（活动配置了用户）的免费卡券营销活动信息!", globalInstId, globalUserId);
                return null;
            }

            int totalPage = pageResult.getPageInfo().getTotalPage();
            if (CommonConstant.ZERO == totalPage) {
                return null;
            }

            List<TMMcCouponInfo> tmMcCouponInfoList = pageResult.getResult().stream().map(object -> (TMMcCouponInfo) object).collect(Collectors.toList());

            /* 取对应卡券营销活动的可领取卡券,每个营销活动只取一张卡券 */
            List<TMCouponInfo> tmCouponInfoList1 = selectAvailableCouponInfo(tmMcCouponInfoList);

            //如果取到的卡券不为null，则添加到卡券信息列表
            if (null != tmCouponInfoList1 && !tmCouponInfoList1.isEmpty()) {
                tmCouponInfoList.addAll(tmCouponInfoList1);
                rglog.debug("去重前卡券集合<{}>", JSONObject.toJSONString(tmCouponInfoList));
                tmCouponInfoList = tmCouponInfoList.stream().distinct().collect(Collectors.toList());
                rglog.debug("去重后卡券集合<{}>", JSONObject.toJSONString(tmCouponInfoList));
            }

            /* 如果获取到3张卡券,则返回退出循环并返回,如果未领取到足够卡券,则继续流程 */
            if (couponQty <= tmCouponInfoList.size()) {
                return tmCouponInfoList;
            } else {
                pageIndex = pageIndex + CommonConstant.ONE;
                pageInfo.setPageIndex(pageIndex);

                if (pageIndex >= totalPage) {
                    /* 已查询到最后一页,如果已取到数据,按取到的数据返回,如果无数据,返回null */
                    if (tmCouponInfoList.isEmpty()) {
                        rglog.info("未获取到可领取的用户在白名单中的免费卡券信息!");
                        return null;
                    } else {
                        return tmCouponInfoList;
                    }
                }
            }
        }

        return null;
    }

    /**
     * 取用户可领取的未限定用户白名单的卡券营销活动的卡券
     *
     * @param couponQty 剩余可领取卡券数量
     * @return java.util.List<cc.rengu.igas.momp.common.entity.TMCouponInfo> 卡券信息表
     * @throws Exception 异常信息
     * @author Jinan Liu
     * @since 2020/6/8 18:01
     */
    private List<TMCouponInfo> getFreeCouponWithouUserWhiteList(int couponQty, List<TMCouponInfo> twoTmCouponInfoList) throws Exception {

        int pageIndex = CommonConstant.ZERO;

        PageInfo pageInfo = new PageInfo();
        pageInfo.setPageIndex(pageIndex);
        pageInfo.setPageSize(couponQty);

        PageResult pageResult;

        CpMcListInfoInObj cpMcListInfoInObj = new CpMcListInfoInObj();
        cpMcListInfoInObj.setInstId(globalInstId);
        cpMcListInfoInObj.setTxnDate(globalTxnDate);

        McDetailInfoMapper mcDetailInfoMapper = new McDetailInfoMapperImpl();

        List<TMCouponInfo> tmCouponInfoList = new ArrayList<>();

        while (COUPON_QTY >= twoTmCouponInfoList.size()) {

            /* 查询未限制用户白名单中的免费券的卡券类营销活动 */
            pageResult = mcDetailInfoMapper.selectCouponMcInfoWithoutUserWhiteList(cpMcListInfoInObj, pageInfo);
            if (null == pageResult || null == pageResult.getPageInfo() || null == pageResult.getResult()) {
                rglog.error("未取到法人机构号<{}>的用户<{}>可参加的未限制用户白名单的卡券营销活动信息!", globalInstId, globalUserId);
                return null;
            }

            int totalPage = pageResult.getPageInfo().getTotalPage();
            if (CommonConstant.ZERO == totalPage) {
                return null;
            }

            rglog.info("取出<{}>个当前用户<{}>可参与的未限制用户白名单的卡券营销活动", pageResult.getResult().size(), globalUserId);

            List<TMMcCouponInfo> tmMcCouponInfoList = pageResult.getResult().stream().map(object -> (TMMcCouponInfo) object).collect(Collectors.toList());
            rglog.debug("分页取出的营销活动<{}>", JSONObject.toJSONString(tmMcCouponInfoList));
            /* 取对应卡券营销活动的可领取卡券,每个营销活动只取一张卡券 */
            List<TMCouponInfo> tmCouponInfoList1 = selectAvailableCouponInfo(tmMcCouponInfoList);

            //如果取到的卡券不为null，则添加到卡券信息列表
            if (null != tmCouponInfoList1 && !tmCouponInfoList1.isEmpty()) {
                tmCouponInfoList.addAll(tmCouponInfoList1);
                rglog.debug("去重前卡券集合<{}>", JSONObject.toJSONString(tmCouponInfoList));
                tmCouponInfoList = tmCouponInfoList.stream().distinct().collect(Collectors.toList());
                rglog.debug("去重后卡券集合<{}>", JSONObject.toJSONString(tmCouponInfoList));
                twoTmCouponInfoList.addAll(tmCouponInfoList);
                twoTmCouponInfoList = twoTmCouponInfoList.stream().distinct().collect(Collectors.toList());
            }


            /* 如果获取到couponQty张卡券,则返回退出循环并返回,如果未领取到足够卡券,则继续流程 */
            if (COUPON_QTY <= twoTmCouponInfoList.size()) {
                return twoTmCouponInfoList;
            } else {
                pageIndex = pageIndex + CommonConstant.ONE;
                pageInfo.setPageIndex(pageIndex);

                if (pageIndex >= totalPage) {
                    /* 已查询到最后一页,如果已取到数据,按取到的数据返回,如果无数据,返回null */
                    if (twoTmCouponInfoList.isEmpty()) {
                        rglog.info("未获取到可领取的用户在白名单中的免费卡券信息!");
                        return null;
                    } else {
                        return twoTmCouponInfoList;
                    }
                }
            }
        }

        return null;
    }

    /**
     * 取用户可领取的限定了用户白名单的测试中卡券营销活动的卡券
     * 最多返回3条数据
     * 如果未取到数据,返回空
     *
     * @return java.util.List<cc.rengu.igas.momp.common.entity.TMCouponInfo> 卡券信息表
     * @throws Exception 异常信息
     * @author JL Pang
     * @since 2020/9/25 17:55
     */
    private List<TMCouponInfo> getTestFreeCouponWithUserWhiteList(int couponQty) throws Exception {

        int pageIndex = CommonConstant.ZERO;

        PageInfo pageInfo = new PageInfo();
        pageInfo.setPageIndex(pageIndex);
        pageInfo.setPageSize(couponQty);

        PageResult pageResult;

        CpMcListInfoInObj cpMcListInfoInObj = new CpMcListInfoInObj();
        cpMcListInfoInObj.setInstId(globalInstId);
        cpMcListInfoInObj.setAcctNo(globalUserId);
        cpMcListInfoInObj.setTxnDate(globalTxnDate);

        McDetailInfoMapper mcDetailInfoMapper = new McDetailInfoMapperImpl();

        List<TMCouponInfo> tmCouponInfoList = new ArrayList<>();

        while (couponQty >= tmCouponInfoList.size()) {

            /* 查询用户在白名单中的免费券的卡券类营销活动 */
            pageResult = mcDetailInfoMapper.selectTestCouponMcInfoWithoutUserWhiteList(cpMcListInfoInObj, pageInfo);
            if (null == pageResult || null == pageResult.getPageInfo() || null == pageResult.getResult()) {
                rglog.error("未取到法人机构号<{}>的用户<{}>可参加的限制用户白名单（活动配置了用户）的测试中的免费卡券营销活动信息!", globalInstId, globalUserId);
                return null;
            }

            int totalPage = pageResult.getPageInfo().getTotalPage();
            if (CommonConstant.ZERO == totalPage) {
                return null;
            }

            List<TMMcCouponInfo> tmMcCouponInfoList = pageResult.getResult().stream().map(object -> (TMMcCouponInfo) object).collect(Collectors.toList());

            /* 取对应卡券营销活动的可领取卡券,每个营销活动只取一张卡券 */
            List<TMCouponInfo> tmCouponInfoList1 = selectAvailableCouponInfo(tmMcCouponInfoList);

            //如果取到的卡券不为null，则添加到卡券信息列表
            if (null != tmCouponInfoList1 && !tmCouponInfoList1.isEmpty()) {
                tmCouponInfoList.addAll(tmCouponInfoList1);
                rglog.debug("去重前卡券集合<{}>", JSONObject.toJSONString(tmCouponInfoList));
                tmCouponInfoList = tmCouponInfoList.stream().distinct().collect(Collectors.toList());
                rglog.debug("去重前卡券集合<{}>", JSONObject.toJSONString(tmCouponInfoList));
            }

            /* 如果获取到3张卡券,则返回退出循环并返回,如果未领取到足够卡券,则继续流程 */
            if (couponQty <= tmCouponInfoList.size()) {
                return tmCouponInfoList;
            } else {
                pageIndex = pageIndex + CommonConstant.ONE;
                pageInfo.setPageIndex(pageIndex);

                if (pageIndex >= totalPage) {
                    /* 已查询到最后一页,如果已取到数据,按取到的数据返回,如果无数据,返回null */
                    if (tmCouponInfoList.isEmpty()) {
                        rglog.info("未获取到可领取的用户在白名单中的测试中的免费卡券信息!");
                        return null;
                    } else {
                        return tmCouponInfoList;
                    }
                }
            }
        }

        return null;
    }

    /**
     * 获取可领取卡券信息
     *
     * @param tmMcCouponInfoList 卡券类营销活动信息表
     * @return java.util.List<cc.rengu.igas.momp.common.entity.TMCouponInfo> 卡券信息表
     * @throws Exception 异常信息
     * @author Jinan Liu
     * @since 2020/6/8 14:31
     */
    private List<TMCouponInfo> selectAvailableCouponInfo(List<TMMcCouponInfo> tmMcCouponInfoList) throws Exception {

        CouponInfoMapper couponInfoMapper = new CouponInfoMapperImpl();
        List<TMCouponInfo> tmCouponInfoList = new ArrayList<>();
        //卡券类营销活动信息表
        for (TMMcCouponInfo tmMcCouponInfo : tmMcCouponInfoList) {
            rglog.info("判断活动<{}>是否是配置了卡bin的活动", tmMcCouponInfo.getMcNo());
            if (CommonConstant.SPECIFIC_CLIENT_SUPPORT.equals(tmMcCouponInfo.getClientRange())) {
                rglog.info("活动<{}>客户范围为指定用户,继续判断是否是否配置了卡bin", tmMcCouponInfo.getMcNo());
                List<TMMcUserInfo> userInfoList = selectMcUserInfoList(tmMcCouponInfo.getInstId(), tmMcCouponInfo.getMcNo());
                if (null != userInfoList && !userInfoList.isEmpty()) {
                    if (CommonConstant.TWO_COMMON_CONSTANT.equals(userInfoList.get(0).getAcctType())) {
                        rglog.info("活动<{}>客户范围为指定用户且为卡bin 活动次数限制不在此判断", tmMcCouponInfo.getMcNo());
                        TMCouponInfo tmCouponInfo = couponInfoMapper.selectSingleClaimableCouponbyMcNo(tmMcCouponInfo.getInstId(), tmMcCouponInfo.getMcNo());
                        if (null == tmCouponInfo) {
                            rglog.info("法人机构<{}>的卡券营销活动<{}>无可领取卡券!", tmMcCouponInfo.getInstId(), tmMcCouponInfo.getMcNo());
                        } else {
                            //活动门槛 criteria
                            BigDecimal criteria = new BigDecimal(tmCouponInfo.getCriteria()).setScale(CommonConstant.DECIMAL_SCALE_TWO, RoundingMode.HALF_UP);
                            //卡券可抵扣金额  couponAmt
                            BigDecimal couponAmt = new BigDecimal(tmCouponInfo.getCouponAmt()).setScale(CommonConstant.DECIMAL_SCALE_TWO, RoundingMode.HALF_UP);

                            if (CommonConstant.ZERO < criteria.compareTo(couponAmt)) {
                                tmCouponInfoList.add(tmCouponInfo);
                            }
                        }
                        continue;
                    }
                }
            }

            //获取营销活动限制次数
            int restriction = Integer.parseInt(tmMcCouponInfo.getRestriction());
            //获取用户领券次数
            TMCouponInfo tmCouponInfo1 = couponInfoMapper.selectUserCouponCountByMarketingPlatform(tmMcCouponInfo.getMcNo(), globalUserId);
            int couponCount = Integer.parseInt(CommonConstant.ZERO_COMMON_CONSTANT);
            if (null != tmCouponInfo1) {
                couponCount = Integer.parseInt(tmCouponInfo1.getRemark4());
            }
            if (restriction > couponCount) {
                TMCouponInfo tmCouponInfo = couponInfoMapper.selectSingleClaimableCouponbyMcNo(tmMcCouponInfo.getInstId(), tmMcCouponInfo.getMcNo());
                if (null == tmCouponInfo) {
                    rglog.info("法人机构<{}>的卡券营销活动<{}>无可领取卡券!", tmMcCouponInfo.getInstId(), tmMcCouponInfo.getMcNo());
                } else {
                    //活动门槛 criteria
                    BigDecimal criteria = new BigDecimal(tmCouponInfo.getCriteria()).setScale(CommonConstant.DECIMAL_SCALE_TWO, RoundingMode.HALF_UP);
                    //卡券可抵扣金额  couponAmt
                    BigDecimal couponAmt = new BigDecimal(tmCouponInfo.getCouponAmt()).setScale(CommonConstant.DECIMAL_SCALE_TWO, RoundingMode.HALF_UP);

                    if (CommonConstant.ZERO < criteria.compareTo(couponAmt)) {
                        tmCouponInfoList.add(tmCouponInfo);
                    }
                }
            }
        }

        if (tmCouponInfoList.isEmpty()) {
            return null;
        } else {
            return tmCouponInfoList;
        }
    }

    /**
     * 根据卡券信息查询对应卡券营销活动的卡券规则信息
     *
     * @param tmCouponInfoList 卡券信息表
     * @return java.util.List<cc.rengu.igas.momp.common.entity.TMMcCouponRuleInfo> 卡券类营销活动规则信息表
     * @throws Exception 异常信息
     * @author Jinan Liu
     * @since 2020/6/8 15:26
     */
    private List<TMMcCouponRuleInfo> selectCouponRuleInfo(List<TMCouponInfo> tmCouponInfoList) throws Exception {

        List<TMMcCouponRuleInfo> tmMcCouponRuleInfoList = new ArrayList<>();

        McRuleInfoMapper mcRuleInfoMapper = new McRuleInfoMapperImpl();

        for (TMCouponInfo tmCouponInfo : tmCouponInfoList) {

            TMMcCouponRuleInfo tmMcCouponRuleInfo = mcRuleInfoMapper.selectCouponRuleInfoByPrimaryKey(tmCouponInfo.getInstId(), tmCouponInfo.getMcNo(), tmCouponInfo.getRuleIndex());
            if (null == tmMcCouponRuleInfo) {
                rglog.error("获取法人机构号<{}>卡券营销活动编号<{}>规则顺序号<{}>的卡券规则失败!", tmCouponInfo.getInstId(), tmCouponInfo.getMcNo(), tmCouponInfo.getRuleIndex());
                return null;
            } else {
                /* 生成卡券规则描述 */
                tmCouponInfo.setRuleContent(generateCouponRuleContent(tmMcCouponRuleInfo));

                /* 返回LIST */
                tmMcCouponRuleInfoList.add(tmMcCouponRuleInfo);
            }
        }

        return tmMcCouponRuleInfoList;
    }


    /**
     * 卡券信息实体类转换应答报文实体类
     *
     * @param tmCouponInfo 卡券信息表
     * @return cc.rengu.igas.momp.facade.bean.PostPaymentAvailableCouponMcInfoBean 卡券类优惠信息对象
     * @author Jinan Liu
     * @since 2020/6/8 14:29
     */
    private PostPaymentAvailableCouponMcInfoBean convertCouponInfo(TMCouponInfo tmCouponInfo) {

        PostPaymentAvailableCouponMcInfoBean postPaymentAvailableCouponMcInfoBean = new PostPaymentAvailableCouponMcInfoBean();

        try {

            /* 营销活动编号 */
            postPaymentAvailableCouponMcInfoBean.setMcNo(tmCouponInfo.getMcNo());
            /* 商户号 */
            postPaymentAvailableCouponMcInfoBean.setMchntNo(CommonConstant.WHITE_SPACE);
            /* 卡券编号 */
            postPaymentAvailableCouponMcInfoBean.setCouponNo(CommonConstant.ONE_STAR);
            /* 卡券有效起始日期 */
            postPaymentAvailableCouponMcInfoBean.setCouponStartDate(tmCouponInfo.getCouponStartDate());
            /* 卡券有效结束日期 */
            postPaymentAvailableCouponMcInfoBean.setCouponEndDate(tmCouponInfo.getCouponEndDate());
            /* 规则编号 */
            postPaymentAvailableCouponMcInfoBean.setRuleIndex(tmCouponInfo.getRuleIndex());
            /* 卡券面额 */
            postPaymentAvailableCouponMcInfoBean.setDenomination(tmCouponInfo.getCouponAmt());
            /* 卡券购买金额 */
            postPaymentAvailableCouponMcInfoBean.setPurchaseAmt(CommonConstant.ZERO_AMOUNT);
            /* 卡券规则描述 */
            postPaymentAvailableCouponMcInfoBean.setRuleContent(tmCouponInfo.getRuleContent());

            createCouponOprLog(tmCouponInfo);

        } catch (Exception e) {
            rglog.error("转换卡券异常,异常信息:<{}>", StringUtil.ExceptionToString(e));
            throw new BizException(RespCodeEnum.SYSTEM_ERROR.getRespCode(), RespCodeEnum.SYSTEM_ERROR.getRespDesc());
        }
        return postPaymentAvailableCouponMcInfoBean;
    }

    /**
     * 根据卡券规则信息生成卡券规则信息描述
     *
     * @param tmMcCouponRuleInfo 卡券类营销活动规则信息表
     * @return java.lang.String 卡券规则信息描述
     * @author Jinan Liu
     * @since 2020/6/2 21:45
     */
    private String generateCouponRuleContent(TMMcCouponRuleInfo tmMcCouponRuleInfo) {

        BigDecimal criteria = new BigDecimal(tmMcCouponRuleInfo.getCriteria()).setScale(CommonConstant.DECIMAL_SCALE_TWO, RoundingMode.HALF_UP);
        BigDecimal denomination = new BigDecimal(tmMcCouponRuleInfo.getDenomination()).setScale(CommonConstant.DECIMAL_SCALE_TWO, RoundingMode.HALF_UP);

        return "满" + criteria.toString() + "减" + denomination.toString();
    }

    /**
     * 报文检查及全局变量赋值
     *
     * @param queryAvailableDiscountInfoAfterPaymentRequest 支付成功可优惠信息查询接口请求对象
     * @throws Exception 异常信息
     * @author Jinan Liu
     * @date 2020/8/19 12:02
     */
    private void messageValidation(QueryAvailableDiscountInfoAfterPaymentRequest queryAvailableDiscountInfoAfterPaymentRequest) throws BizException {

        if (StringUtil.isNullorEmpty(queryAvailableDiscountInfoAfterPaymentRequest.getHeader().getTransDate())) {
            rglog.error("交易日期必须上送!");
            throw new BizException(RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespCode(), RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespDesc());
        } else {
            globalTxnDate = queryAvailableDiscountInfoAfterPaymentRequest.getHeader().getTransDate();
        }

        if (StringUtil.isNullorEmpty(queryAvailableDiscountInfoAfterPaymentRequest.getHeader().getTransTime())) {
            rglog.error("交易时间必须上送!");
            throw new BizException(RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespCode(), RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespDesc());
        } else {
            globalTxnTime = queryAvailableDiscountInfoAfterPaymentRequest.getHeader().getTransTime();
        }

        if (StringUtil.isNullorEmpty(queryAvailableDiscountInfoAfterPaymentRequest.getHeader().getInstId())) {
            rglog.error("法人机构号必须上送!");
            throw new BizException(RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespCode(), RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespDesc());
        } else {
            globalInstId = queryAvailableDiscountInfoAfterPaymentRequest.getHeader().getInstId();
        }

        if (StringUtil.isNullorEmpty(queryAvailableDiscountInfoAfterPaymentRequest.getHeader().getTraceNo())) {
            rglog.error("流水号必须上送!");
            throw new BizException(RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespCode(), RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespDesc());
        } else {
            globalTraceNo = queryAvailableDiscountInfoAfterPaymentRequest.getHeader().getTraceNo();
        }

        globalUserId = queryAvailableDiscountInfoAfterPaymentRequest.getUserId();
        if (!StringUtil.isNullorEmpty(globalUserId)) {
            boolean isJson = isJson(globalUserId);
            if (isJson) {
                userIdFlag = CommonConstant.THREE_COMMON_CONSTANT;
                rglog.info("上送userId为Json字符串,phoneNo<{}>,cardNo<{}>,wechatId<{}>,alipayId<{}>,coreComId<{}>,userIdFlag<{}>", phoneNo, cardNo, wechatId, alipayId, coreComId, userIdFlag);
                globalUserId = getUserList();
            } else {
                userIdFlag = CommonConstant.TWO_COMMON_CONSTANT;
                rglog.info("上送userId<{}>", globalUserId);
            }
        } else {
            userIdFlag = CommonConstant.ONE_COMMON_CONSTANT;
            rglog.info("未上送userId");
        }
        if (StringUtil.isNullorEmpty(queryAvailableDiscountInfoAfterPaymentRequest.getHeader().getSrcSysId())) {
            rglog.error("需要上送源系统标识!");
            throw new BizException(RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespCode(), RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespDesc());
        } else {
            globalsSrcSysId = queryAvailableDiscountInfoAfterPaymentRequest.getHeader().getSrcSysId();
        }

        globalTimeStamp = new SimpleDateFormat(CommonConstant.TIMESTAMP_FORMAT).format(new Date());

        tmTxnBizOpList = new ArrayList<>();
    }

    /**
     * 卡券类活动业务操作流水表实体类列表数据转换
     *
     * @param tmCouponInfo 卡券信息表
     * @author Jinan Liu
     * @date 2020/8/19 10:57
     */
    private void createCouponOprLog(TMCouponInfo tmCouponInfo) {

        TMTxnBizOp tmTxnBizOp = new TMTxnBizOp();
        tmTxnBizOp.setInstId(globalInstId);
        tmTxnBizOp.setTxnDate(globalTxnDate);
        tmTxnBizOp.setTxnTime(globalTxnTime);
        tmTxnBizOp.setTxnNum(MompTxnNumEnum.AVAIL_DISCOUNT_AFTER_QUERY.getTxnNum());
        tmTxnBizOp.setMsgSrcId(globalsSrcSysId);
        tmTxnBizOp.setSysSeqNum(globalTraceNo);
        tmTxnBizOp.setMcNo(tmCouponInfo.getMcNo());
        tmTxnBizOp.setBizOprType(QueryTypeEnum.USER_QYERY_TYPE.getQueryTypeCode());
        //业务流水表 操作主体字段存单个userId
        if (CommonConstant.THREE_COMMON_CONSTANT.equals(userIdFlag)) {
            if (!StringUtil.isNullorEmpty(phoneNo)) {
                tmTxnBizOp.setBizOprId(phoneNo);
            } else if (!StringUtil.isNullorEmpty(cardNo)) {
                tmTxnBizOp.setBizOprId(cardNo);
            } else if (!StringUtil.isNullorEmpty(alipayId)) {
                tmTxnBizOp.setBizOprId(alipayId);
            } else if (!StringUtil.isNullorEmpty(wechatId)) {
                tmTxnBizOp.setBizOprId(wechatId);
            } else {
                tmTxnBizOp.setBizOprId(coreComId);
            }
        } else {
            tmTxnBizOp.setBizOprId(globalUserId);
        }
        tmTxnBizOp.setBizOprOrgId(CommonConstant.DEFAULT_ORG_ID);
        tmTxnBizOp.setBizOprRole(QueryRoleEnum.USER_QYERY_ROLE.getQueryRoleCode());
        tmTxnBizOp.setBizOprStatus("1");
        tmTxnBizOp.setOprId(CommonConstant.DEFAULT_OPR_ID);
        tmTxnBizOp.setCreateTime(globalTimeStamp);

        tmTxnBizOpList.add(tmTxnBizOp);
    }

    /**
     * 判断上送userId是否为json字符串
     *
     * @param userId
     * @return
     * @author pangjl
     * @date 2021.04.21
     */
    public boolean isJson(String userId) {
        try {
            JSONObject jsonObject = JSON.parseObject(userId);
            phoneNo = jsonObject.getString("phoneNo");
            cardNo = jsonObject.getString("cardNo");
            wechatId = jsonObject.getString("wechatId");
            alipayId = jsonObject.getString("alipayId");
            coreComId = jsonObject.getString("coreComId");
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 获取卡号所属卡bin
     *
     * @param userId
     * @return
     * @throws Exception
     * @author pangjl
     * @date 2021.08.20
     */
    private String getCardBin(String userId) throws Exception {
        //查询上送用户的卡bin信息
        BinInfoService binInfoService = new BinInfoServiceImpl();
        BinInfo binInfo = binInfoService.getCardBinInfo(userId);
        if (null != binInfo) {
            String binNo = binInfo.getBinNo();
            rglog.info("通过用户号<{}> 查询卡bin信息为 <{}>！", userId, binNo);
            userId = userId + "," + binNo;
        } else {
            rglog.info("通过用户号<{}> 查询卡bin信息为空！", userId);
        }

        return userId;
    }

    /**
     * 查询活动下用户信息
     *
     * @param instId 机构号
     * @param mcNo   活动号
     * @return
     * @throws Exception
     */
    private List<TMMcUserInfo> selectMcUserInfoList(String instId, String mcNo) throws Exception {
        McUserInfoMapper mcUserInfoMapper = new McUserInfoMapperImpl();
        List<TMMcUserInfo> tmMcUserInfoList = mcUserInfoMapper.selectMcUserInfoList(instId, mcNo);
        return tmMcUserInfoList;
    }

    /**
     * 根据上送的json字符串 用逗号拼接
     *
     * @return
     * @author liujinan
     * @date 20201.9.1
     */
    private String getUserList() {
        String userIdList = "";
        if (!StringUtil.isNullorEmpty(phoneNo)) {
            userIdList = userIdList + phoneNo + ",";
        }
        if (!StringUtil.isNullorEmpty(cardNo)) {
            userIdList = userIdList + cardNo + ",";
        }
        if (!StringUtil.isNullorEmpty(wechatId)) {
            userIdList = userIdList + wechatId + ",";
        }
        if (!StringUtil.isNullorEmpty(alipayId)) {
            userIdList = userIdList + alipayId + ",";
        }
        if (!StringUtil.isNullorEmpty(coreComId)) {
            userIdList = userIdList + coreComId + ",";
        }
        return userIdList;
    }
}
